<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Design extends Model
{
    use HasFactory;

    protected $guarded = [''];

    public function download($user_id)
    {
        try{
            // 查询用户信息
            $user = User::query()->where('state',1)->where('id',$user_id)->first();
            if (!$user) throw new \Exception('用户不存在');

            // 查询下载扣除积分情况
            $config = Config::query()->where('key','downIntegral')->first();
            if (!$config) throw new \Exception('未配置下载扣除积分');
            $integral = intval($config->val);

            if ($integral > $user->inter)  throw new \Exception('用户积分不足');

            if ($integral > 0){
                // 用户扣除积分
                $user->decIntegral($integral);

                // 添加积分记录
                Record::query()->create([
                    'mode' => 0,
                    'name' => '制作刘海壁纸扣除积分',
                    'integral' => $integral,
                    'user_id' => $user->id
                ]);
            }

            return true;
        }catch (\Exception $exception){
            Log::channel('daily')->error('Line:' . $exception->getLine(). ' Message:'.$exception->getMessage());
            return false;
        }
    }
}
